package com.andyliu.sys.controller;

import com.andyliu.sys.pojo.SUser;
import com.andyliu.sys.service.RoleService;
import com.andyliu.sys.service.UserService;
import com.andyliu.util.JWT;
import com.andyliu.util.JwtUtil;
import com.andyliu.vo.LoginVO;
import com.andyliu.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * ClassName: LoginController
 * Description: TODO
 * date: 2021/1/21 3:59 下午
 *
 * @author andyliu
 * @since JDK 1.8
 */
@RestController
@Api(tags = "登陆退出请求",produces = "application/josn",protocols = "http")
public class LoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @PostMapping("/login")
    @ApiOperation(value = "用户登陆",notes = "登陆请求验证")
    public Result<Object> login(@ApiParam(
            value = "user",
            name="输入用户名和密码"
    ) @RequestBody LoginVO user,@ApiIgnore @SessionAttribute String code){
        Subject subject = SecurityUtils.getSubject();
        String loginToken="";
        if(code==null || !user.getCode().equalsIgnoreCase(code.toString())){
            return Result.error(1002,"验证码错误");
        }
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName() ,user.getPwd());
       try {
           subject.login(token);

       }catch (UnknownAccountException ex){
           return Result.error(1000,"用户名不存在");
       }catch (AuthenticationException ex){
           return Result.error(1001,"密码不正确");
       }
        // 获取登陆成功的用户名
        SUser userInfo = userService.selectUser(user.getUserName(),user.getPwd());
        loginToken = JWT.sign(userInfo, 1000 * 60 * 20);
        Map map = new HashMap<String,Object>();
        List<String> permissions = roleService.selectPermission(userInfo.getRoleid());
        loginToken = JwtUtil.createJWT(userInfo.getId().toString(),userInfo.getUsername(),"");
        map.put("userId",userInfo.getId());
        map.put("token",loginToken);
        map.put("permissions",permissions);
        return Result.ok("登陆成功",map);
    }
    @GetMapping("/logout")
    @ApiOperation(value ="退出登陆",notes ="退出登陆" )
    public Result<Object> logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        Result<Object> result = Result.ok("",true);
        return result;
    }
}
